package org.lex.game.sudoku.view;

import java.awt.Color;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.GridLayout;

import javax.swing.BorderFactory;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.SwingConstants;
import javax.swing.border.Border;
import javax.swing.border.TitledBorder;

import ms.sudoku.util.IntSet;

public class CellHintPane extends JPanel {
	private static final long serialVersionUID = -8733998313417382288L;

	private int gridSize = -1;
	private int boxSize = -1;

	private JLabel[][] cells = null;

	private Border border = BorderFactory.createLineBorder(Color.LIGHT_GRAY);

	public CellHintPane() {
		this.setBorder(new TitledBorder(null, "Hints", TitledBorder.CENTER, TitledBorder.TOP, null, null));
	}

	public void setHints(int gridSize, int boxSize, IntSet hints) {
		if (gridSize != this.gridSize || boxSize != this.boxSize) {
			this.gridSize = gridSize;
			this.boxSize = boxSize;
			this.prepare();
		}
		for (int row = 1; row <= this.boxSize; row++) {
			for (int col = 1; col <= this.boxSize; col++) {
				JLabel label = this.cells[row - 1][col - 1];
				int num = (row - 1) * boxSize + col;
				if (true == hints.contains(num)) {
					// show
					label.setText(Integer.toString(num));
					label.setBorder(border);
				} else {
					// hide
					label.setText("");
					label.setBorder(null);
				}
			}
		}
	}

	public void clearHints() {
		if (null != this.cells) {
			for (int row = 0; row < cells.length; row++) {
				for (int col = 0; col < cells[row].length; col++) {
					cells[row][col].setText("");
					cells[row][col].setBorder(null);
				}
			}
		}
	}

	private void prepare() {
		if (null != this.cells) {
			for (JLabel[] row : cells) {
				for (JLabel cell : row) {
					cell.setVisible(false);
					this.remove(cell);
				}
			}
		}
		this.setLayout(new GridLayout(this.boxSize, this.boxSize));
		this.cells = new JLabel[this.boxSize][this.boxSize];
		for (int row = 0; row < this.boxSize; row++) {
			for (int col = 0; col < this.boxSize; col++) {
				JLabel label = new JLabel();
				label.setHorizontalAlignment(SwingConstants.CENTER);
				label.setVerticalAlignment(SwingConstants.CENTER);
				label.setPreferredSize(new Dimension(40, 40));
				label.setFont(new Font(Font.DIALOG, Font.BOLD, 32));

				this.add(label);
				cells[row][col] = label;
			}
		}
	}
}
